package com.whu.util;

/**
 * @Description
 * @Author chengeng
 * @Date 2021/10/28 17:04
 **/
public class CRC16Util {
    /**
     * @Description:使用CRC16 MODBUS标准获取CRC16位校验码
     * @Param [bytes]
     * @return short
     * @Author chengeng
     * @Date 2021/10/18 17:31
     **/
    public static short getCRC(byte[] bytes) {
        // CRC寄存器全为1
        int CRC = 0x0000ffff;
        // 多项式校验值
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return (short) CRC;
    }
}
